<?php

namespace application\admin\controller;

use ticky\request;
use ticky\config;

class content extends base {

    private $modelid, $modeltable, $modelname;

    // 首页
    public function index() {
        $search = $this->search_frm();
        $this->modelid = isset($_GET['modelid']) ? intval($_GET['modelid']) : 1;
        $this->public_set_modelinfo();
        $model = db('model')->where(['modelid' => $this->modelid])->find();
        $modeltable = isset($model['tablename']) ? $model['tablename'] : 'news';
        $prefix = config::get('db')['prefix'];
        $ret = db('content a')
                ->field('a.*')
                ->join($prefix . '' . $modeltable . " g on a.contentid=g.contentid")
                ->where($search['sql'])
                ->newpage();
        $data = array();
        foreach ($ret['items'] as $row) {
            $level = "";
            if ($row['thumb']) {
                $level = '<span style="color:#0a6999;margin:0 3px" title="图片"><i class="fa fa-picture-o" aria-hidden="true"></i></span>';
            }
            $flg = "";
            if (strpos($row['flag'], '1') !== false) {
                $flg .= '<span class="red">[置顶]</span>';
            }
            if (strpos($row['flag'], '2') !== false) {
                $flg .= '<span class="red">[头条]</span>';
            }
            if (strpos($row['flag'], '3') !== false) {
                $flg .= '<span class="red">[特荐]</span>';
            }
            if (strpos($row['flag'], '4') !== false) {
                $flg .= '<span class="red">[推荐]</span>';
            }
            if (strpos($row['flag'], '5') !== false) {
                $flg .= '<span class="red">[热点]</span>';
            }
            if (strpos($row['flag'], '6') !== false) {
                $flg .= '<span class="red">[幻灯]</span>';
            }
            if (strpos($row['flag'], '7') !== false) {
                $flg .= '<span class="red">[跳转]</span>';
            }
            if ($row['readpoint']) {
                $flg .= '<span class="red">[付费]</span>';
            }
            $item = db('category')->where('catid=' . $row['catid'])->find();
            $row['catname'] = $item['catname'];
            $row['level'] = $level . $flg;
            $row['edit_url'] = "/admin/content/update/?action=edit&tablename=" . $modeltable . "&modelid=" . $this->modelid . "&contentid=" . $row['contentid'] . '&catid=' . $row['catid'];
            $row['del_url'] = '/admin/content/delete/?' . "&contentid=" . $row['contentid'] . "&modelid=" . $this->modelid;
            $data[] = $row;
        }
        $this->assign('page', $ret['page']);
        $this->assign('items', $data);
        $this->assign('manage_url', "/admin/content/add/?action=add&tablename=" . $modeltable . "&modelid=" . $this->modelid);
        $this->display('content/index');
    }

    // 添加记录
    public function add() {
        if (request::isPost()) {
            $tablename = request::get('tablename', 'news');
            $data = $this->post_frm();

            $data1 = $_GET;
            $data1['contentid'] = $contentid;
            if ($data1['content']) {
                $data1['content'] = closetags($data1['content']);
            }

            //远程图片本地化
            if (isset($_GET['grab_img'])) {
                $data1['content'] = grab_image($_GET['content']);
            }

            //自动提取缩略图
            if (isset($_GET['auto_thum']) && $data['thumb'] == '') {
                $img = match_img($data1['content']);
                $data['thumb'] = $img ? thumb($img) : '';
            }

            $contentid = db('content')->insert($data);
            //如果不是跳转URL，则更新URL
            if ($data['url'] == '') {
                $url = $this->get_url($data['catid'], $contentid);
                db('content')->update(array('url' => $url), array('contentid' => $contentid));
            }

            db($tablename)->insert($data1, false, false);
            showmsg('添加成功', '/admin/content/?modelid=' . request::get('modelid', 1) . '&catid=' . $data['catid']);
        } else {
            load_extend('content_form.class.php');
            $action = request::get('action', 'add');
            $this->modeltable = request::get('tablename', 'news');
            $this->modelid = isset($_GET['modelid']) ? intval($_GET['modelid']) : 1;

            $this->public_set_modelinfo();

            $sitemodel = getsitemodel();

            $content_form = new \content_form($this->modelid);

            $this->assign('postUrl', '/admin/content/add');
            $this->assign('action', '添加');
            $item['allowcomment'] = 0;
            $item['readperm'] = 0;
            $item['flag'] = "0,0,0,0,0,0,0";
            $item['thumb'] = "/static/common/img/nopic.jpg";
            $item['modelid'] = $this->modelid;
            $this->assign('item', $item);
            $string = $content_form->content_add();

            $this->assign('from', $string);
            $this->assign('modelid', $this->modelid);
            $this->assign('tablename', $this->modeltable);
            $this->assign('modelname', str_replace("模型", "", $this->modelname));
            $this->assign('navtitle', str_replace('模型', '', $sitemodel[$this->modelid]));
            $this->assign('viewfile', 'content/content_' . $this->modeltable);
            $this->display('content/manage');
        }
    }

    // 更新记录
    public function update() {
        if (request::isPost()) {
            $tablename = request::get('tablename', 'news');
            $contentid = request::get('contentid', 0);
            $where = ['contentid' => $contentid];
            $data = $this->post_frm();

            $data1 = $_GET;
            $data1['contentid'] = $contentid;

            //远程图片本地化
            if (isset($_GET['grab_img'])) {
                $data1['content'] = grab_image($_GET['content']);
            }

            //自动提取缩略图
            if (isset($_GET['auto_thum'])) {
                $img = match_img($data1['content']);
                $data['thumb'] = $img ? thumb($img) : '';
            }

            if ($data['thumb'] == '') {
                $data['thumb'] = '/static/common/img/nopic.jpg';
            }

            //如果不是跳转URL，则更新URL
            if (strpos($data['flag'], '7') === false) {
                $data['url'] = $this->get_url($data['catid'], $contentid);
            }
            db('content')->update($data, $where);

            db($tablename)->update($data1, $where);
            showmsg('更新成功', '/admin/content/?modelid=' . request::get('modelid', 1) . '&catid=' . request::get('catid', 1));
        } else {
            load_extend('content_form.class.php');
            $action = request::get('action', 'update');
            $tablename = request::get('tablename', 'news');
            $modelid = request::get('modelid', 1);
            $sitemodel = getsitemodel();
            $content_form = new \content_form($modelid);

            $contentid = request::get('contentid', 0);
            $model = db('model')->where(['modelid' => $modelid])->find();
            $content = db('content')->where(['contentid' => $contentid])->find();
            $model_content = db($model['tablename'])->where(['contentid' => $contentid])->find();
            if (!$content['thumb']) {
                $content['thumb'] = "/static/common/img/nopic.jpg";
            }
            $item = array_merge($content, $model_content);
            $this->assign('postUrl', '/admin/content/update');
            $this->assign('action', '修改');
            $this->assign('item', $item);
            $string = $content_form->content_edit($item);

            $this->assign('from', $string);
            $this->assign('modelid', $modelid);
            $this->assign('tablename', $tablename);
            $this->assign('navtitle', str_replace('模型', '', $sitemodel[$modelid]));
            $this->assign('viewfile', 'content/content_' . $tablename);
            $this->display('content/manage');
        }
    }

    // 删除记录
    public function delete() {
        $id = request::get('contentid', 0);
        $content = db('content')->where(array('contentid' => $id))->find();
        $model = db('model')->where(['modelid' => $content['modelid']])->find();
        if (is_array($model)) {
            $modeltable = $model['tablename'];
            db($modeltable)->delete(['contentid' => $id]);
            db('content')->delete(['contentid' => $id]);
        }
        showmsg('删除成功', '/admin/content/?modelid=' . $content['modelid']);
    }

    // 批量删除
    public function batchremove() {
        $optype = request::post('optype', 'del');
        $ids = request::post('ids', []);
        if ($optype == "del") {
            for ($i = 0; $i < count($ids); $i++) {
                $id = $ids[$i];
                $content = db('content')->where(['contentid' => $id])->find();
                if (is_array($content)) {
                    $model = db('model')->where(['modelid' => $content['modelid']])->find();
                    if (is_array($model)) {
                        $modeltable = $model['tablename'];
                        db($modeltable)->delete(['contentid' => $id]);
                        db('content')->delete(['contentid' => $id]);
                    }
                }
            }
            showmsg('删除成功', '/admin/content');
        } else if ($optype == 'baidu') {
            //百度主动推送
            $idstr = join(',', $ids);
            $data = db('content')->field('url,is_push')->where('contentid IN (' . $idstr . ')')->select();
            $urls = array();
            foreach ($data as $value) {
                if ($value['is_push'])
                    continue;
                $urls[] = $value['url'];
            }
            if (!empty($urls)) {
                $baidu_push_token = get_config('baidu_push_token');
                if (!$baidu_push_token)
                    showmsg('token值为空，请到系统设置中配置！', 'stop');
                $api_url = 'http://data.zz.baidu.com/urls?site=' . HTTP_HOST . '&token=' . $baidu_push_token;
                $ch = curl_init();
                $options = array(
                    CURLOPT_URL => $api_url,
                    CURLOPT_POST => true,
                    CURLOPT_RETURNTRANSFER => true,
                    CURLOPT_POSTFIELDS => implode("\n", $urls),
                    CURLOPT_HTTPHEADER => array('Content-Type: text/plain'),
                );
                curl_setopt_array($ch, $options);
                $result = curl_exec($ch);
                curl_close($ch);
                $result = json_decode($result, true);
                if (isset($result['success'])) {
                    db('content')->update(array('is_push' => 1), 'id IN (' . $ids . ')');
                    showmsg('成功推送' . $result['success'] . '条URL地址！', '', 2);
                } else {
                    showmsg('推送失败，错误码：' . $result['error'], 'stop');
                }
            }
            showmsg('百度主动推送成功', '/admin/content');
        }
    }

    //查询条件
    private function search_frm() {
        $where = '1=1 ' . 'and siteid=' . $this->siteid . ' ';
        $modelid = request::get('modelid', 0);
        if ($modelid > 0) {
            $where .= " and modelid = '{$modelid}' ";
        }
        $catid = request::get('catid', 0);
        if ($catid > 0) {
            $where .= " and catid = '{$catid}' ";
        }
        if (isset($_GET["startdate"]) && $_GET["startdate"] != '' && $_GET["enddate"]) {
            $where .= ' AND updatetime BETWEEN ' . strtotime($_GET["startdate"]) . ' AND ' . strtotime($_GET["enddate"]);
        }
        $title = request::get('title', '');
        if ($title != '') {
            $where .= ' AND  CONCAT(IFNULL(`title`,\'\'),IFNULL(`tag`,\'\'),IFNULL(`description`,\'\')) LIKE \'%' . $title . '%\'';
        }
        return [
            'sql' => $where
        ];
    }

    //表单数据
    private function post_frm() {
        $flag = request::post('flag', []);
        $arr = array();
        $arr['modelid'] = request::post('modelid', '');
        $arr['catid'] = request::post('catid', '');
        $arr['siteid'] = $this->siteid;
        $arr['uid'] = $this->uid;
        $arr['title'] = request::post('title', '');
        $arr['description'] = request::post('description', '');
        $arr['url'] = request::post('url', '');
        $arr['thumb'] = request::post('thumb', '');
        $arr['flag'] = implode(",", $flag);
        $arr['tag'] = request::post('tag', '');
        $arr['sort'] = request::post('sort', '0');
        $arr['allowcomment'] = request::post('allowcomment', '0');
        $arr['views'] = request::post('views', '0');
        $arr['replies'] = request::post('replies', '0');
        $arr['readperm'] = request::post('readperm', '0');
        $arr['readpoint'] = request::post('readpoint', '0');
        $arr['is_push'] = request::post('is_push', '0');
        $arr['status'] = request::post('status', '1');
        $arr['inputtime'] = TIMESTAMP;
        $arr['updatetime'] = TIMESTAMP;
        return $arr;
    }

    /**
     * 获取模型信息
     */
    private function public_set_modelinfo() {
        $data = db('model')->field('modelid,name,tablename')->where(array('modelid' => $this->modelid))->find();
        if ($data) {
            $this->modelid = $data['modelid'];
            $this->modelname = $data['name'];
            $this->modeltable = $data['tablename'];

            $this->assign('modelid', $this->modelid);
            $this->assign('modeltable', $this->modeltable);
            $this->assign('modelname', str_replace("模型", "", $this->modelname));
        } else {
            $this->assign('modelid', 1);
            $this->assign('modeltable', 'news');
            $this->assign('modelname', '文章');
        }
    }

}
